package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.TCloudUser;
import model.TSchool;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import annotation.Log;
import persistent.factory.DAOFactory;
import util.toolkit.Constant;
import util.toolkit.Expression;
import util.toolkit.ResponseJSON;

/**
 * 学校信息管理控制类
 * @author djf
 * @since 2018/11/13
 */
@Controller
@RequestMapping(value = "/sysschoolmanagement")
public class SysSchoolController {

	/**
	 * 通过查询条件得到学校信息
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 通过查询条件得到学校信息
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "通过查询条件得到学校信息", 
			operationClassPath = "controller.SysTitleManagementController.getSchoolByWhere(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学校信息管理/学校信息管理")
	@RequestMapping(value = "/getschoolbywhere")
	public String getSchoolByWhere(Model model, HttpServletRequest req,
			HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		Expression exp = new Expression();
		JSONObject result = new JSONObject();

		try {
			String schooltype = req.getParameter("schooltype");
			if (schooltype != null && !schooltype.equals("")) {
				exp.andEqu("schoolType", schooltype, String.class);
			}
			exp.orderByDesc("schoolType");
			String strwhere = exp.toString();

			List<TSchool> list = DAOFactory.getSchoolDAO()
					.getSchoolByCondition(strwhere);
			if (list != null && list.size() > 0) {
				result.put("code", 0);
				result.put("msg", "查询成功！");
				result.put("count", list.size());
				JSONArray jsonArray = JSONArray.fromObject(list);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "未查询到结果！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 2);
			result.put("msg", "出现异常，数据获取失败，请重试！");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}

	/**
	 * 通过查询条件得到一个分页的学校信息
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 通过查询条件得到一个分页的学校信息
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "通过查询条件得到一个分页的学校信息", 
			operationClassPath = "controller.SysTitleManagementController.getSchoolByWherePage(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学校信息管理/学校信息管理")
	@RequestMapping(value = "/getschoolbywherepage")
	public String getSchoolByWherePage(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		Expression exp = new Expression();
		JSONObject result = new JSONObject();

		try {
			String schooltype = req.getParameter("schooltype");
			String schoolname = req.getParameter("schoolname");
			String currentPage = req.getParameter("page");
			String pageSize = req.getParameter("limit");
			if (currentPage != null && pageSize != null) {
				if (schooltype != null && !schooltype.equals("")) {
					exp.andEqu("schoolType", schooltype, String.class);
				}
				if (schoolname != null && !schoolname.equals("")) {
					exp.andLike("schoolName", schoolname, String.class);
				}
				exp.orderByDesc("schoolType");
				exp.orderByDesc("schoolName");
				String strwhere = exp.toString();

				List<TSchool> list = DAOFactory.getSchoolDAO()
						.getSchoolByCondition(strwhere,
								Integer.parseInt(currentPage),
								Integer.parseInt(pageSize));
				List<TSchool> listsize = DAOFactory.getSchoolDAO()
						.getSchoolByCondition(strwhere);
				if (list != null && list.size() > 0) {
					result.put("code", 0);
					result.put("msg", "查询成功！");
					result.put("count", listsize.size());
					JSONArray jsonArray = JSONArray.fromObject(list);
					result.element("data", jsonArray);
				} else {
					result.put("code", 1);
					result.put("msg", "无查询结果！");
				}
			}else{
				result.put("code", 1);
				result.put("msg", "无查询结果！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 2);
			result.put("msg", "出现异常，数据获取失败，请重试！");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}

	/**
	 * 添加一个学校信息 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 添加一个学校信息
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "添加一个学校信息", 
			operationClassPath = "controller.SysTitleManagementController.addSchool(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学校信息管理/学校信息管理")
	@RequestMapping(value = "/addschool")
	public String addSchool(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		
		try {
			String schoolid = req.getParameter("schoolid");
			String schooltype = req.getParameter("schooltype");
			String schoolname = req.getParameter("schoolname");
			String phone = req.getParameter("phone");

			if (schoolid != null && !schoolid.equals("") && schooltype != null
					&& !schooltype.equals("") && schoolname != null
					&& !schoolname.equals("") && phone != null && !phone.equals("")) {
				
				TSchool school = new TSchool();
				school.setSchoolid(schoolid);
				school.setSchoolName(schoolname);
				school.setSchoolType(schooltype);
				
				if(DAOFactory.getSchoolDAO().getTSchool(schoolid) == null){
					if (!DAOFactory.getCloudUserDAO().whetherPhone(phone)) {
						result.put("code", ResponseJSON.FLAG_FAIL);
						result.put("msg", "该用户手机号已被注册！");
					}
					else {
						TCloudUser user = new TCloudUser();
						user.setPhone(phone);
						user.setPwd("123456");
						user.setStatus("启用");
						user.setUserName(schoolid);
						if (DAOFactory.getSchoolDAO().addSchool(school, user)) {
							result.put("code", ResponseJSON.FLAG_SUCC);
							result.put("msg", "添加成功！");
						} else {
							result.put("code", ResponseJSON.FLAG_FAIL);
							result.put("msg", "添加失败，请重试！");
						}
					}				
				}
				else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "该学校编号已存在！");
				}				
			}
			else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "必填项不能为空！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现异常，添加失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}

	/**
	 * 修改一个学校信息
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 修改一个学校信息
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "修改一个学校信息", 
			operationClassPath = "controller.SysTitleManagementController.editSchool(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学校信息管理/学校信息管理")
	@RequestMapping(value = "/editschool")
	public String editSchool(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();

		try {
			String schoolid = req.getParameter("schoolid");
			String schoolname = req.getParameter("schoolname");

			if (schoolid != null && !schoolid.equals("") && schoolname != null
					&& !schoolname.equals("")) {
				TSchool school=DAOFactory.getSchoolDAO().getTSchool(schoolid);
				
				school.setSchoolid(schoolid);
				school.setSchoolName(schoolname);

				boolean row = DAOFactory.getSchoolDAO().updateSchool(school);
				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "修改成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "修改失败，请重试！");
				}
			}else{
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "修改失败，请重试！");
			}

		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现异常，修改失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 删除一个学校(有外键引用不能删除)
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 删除一个学校(有外键引用不能删除)
	@Log(operationType = Constant.OPERTATION_DELETE, operationDescribe = "删除一个学校信息", 
			operationClassPath = "controller.SysTitleManagementController.deleteSchool(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学校信息管理/学校信息管理")
	@RequestMapping(value = "/deleteschool")
	public String deleteSchool(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();

		try {
			String schoolid = req.getParameter("schoolid");
			if (schoolid != null && !schoolid.equals("")) {

				boolean row = DAOFactory.getSchoolDAO().delSchool(schoolid);
				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "删除成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "存在外键引用，该学校不能删除，请删除外键引用后重试！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "学校编号不能为空，删除失败请重试！");
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "出现异常，删除失败请重试！");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}
}
